package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.article.domain.*;
import cn.wolfcode.luowowo.article.query.StrategyCatalogQuery;
import cn.wolfcode.luowowo.article.query.StrategyDetailQuery;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.*;
import cn.wolfcode.luowowo.cache.service.IRedisService;
import cn.wolfcode.luowowo.cache.service.ITravelStatisVOService;
import cn.wolfcode.luowowo.cache.util.RedisKeysUtil;
import cn.wolfcode.luowowo.cache.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.cache.vo.TravelStatisVO;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.utils.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.web.annotation.CheckLoginAnnotation;
import cn.wolfcode.luowowo.website.web.annotation.GetUserInfoAnnotation;
import cn.wolfcode.luowowo.website.web.util.CookieUtil;
import cn.wolfcode.luowowo.website.web.util.UMEditorUploader;
import cn.wolfcode.luowowo.website.web.util.UploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/travel")
public class TravelController {

    @Reference
    private IDestinationService destinationService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private ITravelService travelService;
    @Reference
    private ITravelContentService travelContentService;
    @Reference
    private IRedisService redisService;
    @Reference
    private ITravelCommentService travelCommentService;
    @Reference
    private ITravelStatisVOService travelStatisVOService;
    @RequestMapping("")
    public String destinationList(@ModelAttribute("qo") TravelQuery qo, Model model){
        //pageInfo
        PageInfo<StrategyDetail> pageInfo = travelService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        //tcs 回复动态前10s
        List<TravelComment> list = travelCommentService.getNewTop10();
        for (TravelComment travelComment : list) {
            System.out.println(travelComment.getTravelTitle());
        }
        model.addAttribute("tcs",list);
        return "travel/list";
    }

    @RequestMapping("detail")
    public String get(Long id, Model model,@GetUserInfoAnnotation UserInfo userInfo){
        //detail
        Travel travel =  travelService.get(id);
        TravelContent travelContent = travelContentService.get(travel.getId());
        travel.setTravelContent(travelContent);
        model.addAttribute("detail",travel);

        //toasts
        List<Destination> toasts = destinationService.getToasts(travel.getDest().getId());
        Destination dest = toasts.remove(toasts.size() - 1);
        model.addAttribute("toasts",toasts);

        //sds攻略前三
        List<StrategyDetail> details = strategyDetailService.queryViewNumTop3(travel.getDest().getId());
        model.addAttribute("sds",details);

        //ts游记前三
        List<Travel> travels = travelService.queryViewNumTop3(travel.getDest().getId());
        model.addAttribute("ts",travels);

        //判断是否为访问自己的游记
        boolean b = userInfo.getId() == travel.getAuthor().getId();
        model.addAttribute("b",b);

        //回显评论数据
        TravelCommentQuery qo = new TravelCommentQuery();
        qo.setTravelId(id);
        qo.setPageSize(Integer.MAX_VALUE);
        Page query = travelCommentService.query(qo);
        model.addAttribute("list",query.getContent());


        //阅读数+1
        travelStatisVOService.viewNumIncrease(id,1);
        //传递vo数据
        model.addAttribute("vo",travelStatisVOService.getStatisVONums(id));
        return "travel/detail";
    }

    @RequestMapping("input")
    public String input(Long id, Model model){
        //dests
        List<Destination> dests = destinationService.getDestsByDeep(3);
        model.addAttribute("dests",dests);

        if(id != null) {
            Travel travel = travelService.get(id);
            TravelContent travelContent = travelContentService.get(id);
            travel.setTravelContent(travelContent);
            model.addAttribute("tv", travel);
        }
        return "travel/input";
    }
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    @CheckLoginAnnotation
    //使用参数解析器解析参数达到将解析token转成解析userInfo对象
    //贴@GetUserInfoAnnotation这个标签代表获取Redis里面的UserInfo对象
    public Object saveOrUpdate(Travel travel,@GetUserInfoAnnotation UserInfo userInfo    /*HttpServletRequest req,HttpServletResponse resp*/){
        /*String token = CookieUtil.getToken(req, resp);
        UserInfo userInfo = redisService.getValueByToken(token);
        if (userInfo ==null){
            throw new LogicException("您还没登录,请先登录再操作");
        }*/
        travel.setAuthor(userInfo);
        Long id = travelService.saveOrUpdate(travel);
        return AjaxResult.SUCCESS.addData(id);
    }

    @RequestMapping("commentAdd")
    public String commentAdd(TravelComment comment, Model model,@GetUserInfoAnnotation UserInfo userInfo,int floor){
        comment.setCity(userInfo.getCity());
        comment.setHeadUrl(userInfo.getHeadImgUrl());
        comment.setLevel(userInfo.getLevel());
        comment.setUserId(userInfo.getId());
        comment.setUsername(userInfo.getNickname());

        TravelComment c = travelCommentService.commentAdd(comment);
        model.addAttribute("c",c);
        Long count = travelCommentService.count(comment.getTravelId());
        model.addAttribute("floor",count);
        return "travel/commentTpl";
    }


    @RequestMapping("travelThumbup")
    @ResponseBody
    public Object travelThumbup(Long tid,@GetUserInfoAnnotation UserInfo userInfo){
        if(userInfo == null){
            AjaxResult result = new AjaxResult(false, "您还没登录");
            result.setCode(102);
            return result;
        }
        boolean b = travelStatisVOService.addStrategyThumbup(tid,userInfo.getId());
        TravelStatisVO statisVONums = travelStatisVOService.getStatisVONums(tid);
        return new AjaxResult(b,null).addData(statisVONums);
    }

    @RequestMapping("favor")
    @ResponseBody
    public Object favor(Long tid,@GetUserInfoAnnotation UserInfo userInfo){
        if(userInfo == null){
            AjaxResult result = new AjaxResult(false, "您还没登录");
            result.setCode(102);
            return result;
        }
        boolean b = travelStatisVOService.addFavor(tid,userInfo.getId());
        TravelStatisVO statisVONums = travelStatisVOService.getStatisVONums(tid);
        return new AjaxResult(b,null).addData(statisVONums);
    }
    @RequestMapping("share")
    @ResponseBody
    public Object share(Long tid){
        boolean b = travelStatisVOService.addShare(tid);
        return new AjaxResult(b,null);
    }















    @Value("${file.path}")
    private String fileBasePath;
    //上传图片
    @RequestMapping("/coverImageUpload")
    @ResponseBody
    public Object coverImageUpload(MultipartFile pic){
        String upload = UploadUtil.upload(pic, fileBasePath);
        return upload;
    }

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile,HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, fileBasePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }
}
